package com.isunland.managesystem.base;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.view.View;
import android.widget.EditText;
import com.isunland.managesystem.R;
import com.isunland.managesystem.ui.SimpleListFragment;
import com.isunland.managesystem.utils.LocalSearch;

/**
 * 对象功能: 搜索基类.
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/4/5 14:11
 */

public abstract class BaseSearchListFragment<T> extends SimpleListFragment {
  public static final String EXTRA_ITEM =
      "com.isunland.managesystem.base.BaseSearchListFragment.EXTRA_ITEM";
  protected EditText mSearchEt;

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    //mListview.setDivider(null);
    //noinspection RestrictedApi
    View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.header_search_work_area, mListview,
            false);
    mSearchEt = (EditText) header.findViewById(R.id.et_search_searchPersonHeader);
    ImageSpan imageHint = new ImageSpan(mActivity, R.drawable.ic_search_gray_64);
    SpannableString spannableString = new SpannableString("   搜索");
    spannableString.setSpan(imageHint, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    mSearchEt.setHint(spannableString);
    mSearchEt.addTextChangedListener(new TextWatcher() {

      @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (mListOriginal == null || mListOriginal.size() == 0) {
          return;
        }
        mListTemp.clear();
        if (TextUtils.isEmpty(s)) {
          //noinspection unchecked
          mListTemp.addAll(mListOriginal);
        } else {
          //noinspection unchecked
          mListTemp.addAll(LocalSearch.search(s.toString(), mListOriginal, setQueryField()));
        }
        setAdapter();
        mSearchEt.requestFocus();
      }

      @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override public void afterTextChanged(Editable s) {

      }
    });
    mListview.addHeaderView(header);
  }

  /**
   * 设置可搜索字段
   *
   * @return 可搜索字段,
   */
  protected abstract String[] setQueryField();

  protected void select(T item) {
    Intent i = new Intent();
    if (item instanceof BaseModel) {
      BaseModel model = (BaseModel) item;
      i.putExtra(EXTRA_ITEM, model);
    }
    getActivity().setResult(Activity.RESULT_OK, i);
    getActivity().finish();
  }
}

